package com.lsu.factory.experiment;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Transparency;
import java.awt.image.BufferedImage;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;

/**
 * @author wsuo
 */
public class DrawFrame extends JFrame {
	
	private JPanel panel;

	private DrawFrame(){
		super("测试盖章");
		JToolBar bar = new JToolBar();
		JButton btn = new JButton("盖章");
		btn.addActionListener(e -> {
			Graphics g = panel.getGraphics();

			g.drawImage(drawTransparent(), 100, 80, 256, 256, null);
		});
		panel = new JPanel(){
			@Override
			public void paint(Graphics g){
				g.setFont(new Font("隶书", Font.BOLD, 30));
				g.drawString("床前明月光", 256, 166);
				g.drawString("疑是地上霜", 256, 196);
				g.drawString("举头望明月", 256, 226);
				g.drawString("低头思故乡", 256, 256);
			}
		};
		this.add(bar, BorderLayout.NORTH);
		bar.add(btn);
		this.add(panel);
		this.setSize(640, 480);
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
	}
	
	private static BufferedImage drawTransparent() {
        int width=256;  
        int height=256;  
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
          
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();  
        g2d = image.createGraphics();

		// 画图BasicStroke是JDK中提供的一个基本的画笔类,我们对他设置画笔的粗细，就可以在drawPanel上任意画出自己想要的图形了。
        g2d.setColor(new Color(255, 0, 0));
        g2d.setStroke(new BasicStroke(5f));  
        g2d.drawOval(0, 0, width, height);  
        waxing(g2d, 128, 128, 40);
        g2d.dispose();
        return image;
    }
    private static void waxing(Graphics2D g, int x0, int y0, int r) {
		// 圆心角的弧度数
        double ch = 72 * Math.PI / 180;
        int x2 = (int) (x0 - Math.sin(ch) * r), x3 = (int) (x0 + Math
                .sin(ch) * r), x4 = (int) (x0 - Math.sin(ch / 2) * r), x5 = (int) (x0 + Math
                .sin(ch / 2) * r);
        int y1 = y0 - r, y2 = (int) (y0 - Math.cos(ch) * r), y4 = (int) (y0 + Math
                .cos(ch / 2) * r);

		int bx = (int) (x0 + Math.cos(ch) * Math.tan(ch / 2) * r);

		Polygon a = new Polygon();
        Polygon b = new Polygon();
 
        a.addPoint(x2, y2);
        a.addPoint(x5, y4);
        a.addPoint(bx, y2);
        b.addPoint(x0, y1);
        b.addPoint(bx, y2);
        b.addPoint(x3, y2);
        b.addPoint(x4, y4);
        g.fillPolygon(a);
        g.fillPolygon(b);
    }


	public static void main(String[] args) {
		new DrawFrame();
	}
}
